/*  
 * cafe-dateselect.js
 * @Author :      GUORUI
 * @CreateDate :  2017年10月19日
 * Copyright (c) 2017, NRIET.　
 * 日期控件
 */

;define(function(){
	/**
	 * 创建日期选择界面
	 */
	function buildDateLayer(cfg){
		$(".date-select-wrap").remove();
		var $wrap = $("<div>").addClass("date-select-wrap");
        if(cfg.isRight){
            $wrap.css("right","0");
        }
        $(cfg.appendTo).after($wrap);
		var $operateLayer = $("<div>").addClass("ds-month-year-opera");
		$wrap.append($operateLayer);
        if(cfg.dateFmt.endsWith("yyyy") || cfg.dateFmt.endsWith("MM")){
            buildTimeOperateLayerForYM($operateLayer,cfg);
        }else{
            buildTimeOperateLayer($operateLayer,cfg);
        }
		
		var $dpDateMain = $("<div>").addClass("ds-date-main");
		$wrap.append($dpDateMain);
		
		var $dpDateWrap = $("<div>").addClass("ds-date-wrap");
		$dpDateMain.append($dpDateWrap);
        if(cfg.dateFmt.endsWith("yyyy")){
            buildDateContentForY($dpDateWrap,cfg);
        }else if(cfg.dateFmt.endsWith("MM")){
            buildDateContentForM($dpDateWrap,cfg);
        }else{
            buildDateContent($dpDateWrap,cfg);
        }
		if(-1 != cfg.dateFmt.indexOf("hh")){
			var $dpHmWrap = $("<div>").addClass("ds-hm-wrap");
			$dpDateMain.append($dpHmWrap);
			buildHmLayer($dpHmWrap,cfg);
		}else{
			$wrap.css("height","238px");
			$dpDateMain.css("height","210px");
		}

        bindDateEvent($wrap,cfg);
	}
	/**
	 * 创建日期选择-操作区界面
	 */
	function buildTimeOperateLayer($operateLayer,cfg){
		var showDate = new Date(cfg.curDate);
		var yearStr = showDate.format("yyyy");
		var monthStr = showDate.format("MM");
		$operateLayer.append($('<div>').addClass("ds-year-prev"));
		$operateLayer.append($('<div>').addClass("ds-month-prev"));
		var $dateDiv = $('<div>').addClass("ds-month-year-content");
		$dateDiv.append($('<div>').addClass("ds-month-year-content-year").text(yearStr))
				.append($('<div>').addClass("ds-month-year-content-with").text("年"))
				.append($('<div>').addClass("ds-month-year-content-month").text(monthStr))
				.append($('<div>').addClass("ds-month-year-content-with").text("月"));
		$operateLayer.append($dateDiv);
		$operateLayer.append($('<div>').addClass("ds-month-next"));
		$operateLayer.append($('<div>').addClass("ds-year-next"));
		
		var $ys = $('<div>').addClass("ds-year-select");
		$ys.append($('<div>').addClass("ds-year-area"));
		var $yac = $('<div>').addClass("ds-year-area-control");
		var $yacl = $('<div>').addClass("ds-year-area-controlleft");
		$yacl.append($('<i>').addClass("ds-btn-icon cafe-ifont cafe-ic-xiangyou2"));
		var $yacr = $('<div>').addClass("year-area-controlright");
		$yacr.append($('<i>').addClass("ds-btn-icon cafe-ifont cafe-ic-xiangyou2"));
		$yac.append($yacl).append($yacr);
		$ys.append($yac);
		var $ms = $('<div>').addClass("ds-month-select");
		$.each([1,7,2,8,3,9,4,10,5,11,6,12],function(i,m){
			$ms.append($('<div>').text(m));
		});
		$operateLayer.append($ys).append($ms);
		
	}
    /**
     * 创建日期选择-操作区界面
     */
    function buildTimeOperateLayerForYM($operateLayer,cfg){
        $operateLayer.append($('<div>').addClass("dp-year-prev"));
        var $dateDiv = $('<div>').addClass("dp-month-year-content").css({
            cursor : "default",
            width : "77px",
            margin : "0 64px"
        });
        var showDate = new Date(cfg.curDate);
        var yearStr = showDate.format("yyyy");
        if(cfg.dateFmt.endsWith("yyyy")){
            $dateDiv.css({
                cursor : "default",
                width : "95px",
                margin : "0 55px"
            });
            var startyear = showDate.getFullYear() - 9;
            var endyear = showDate.getFullYear() + 2;
            yearStr =startyear + "-" + endyear;
        }
        $dateDiv.append($('<div>').addClass("dp-month-year-content-year").text(yearStr))
            .append($('<div>').addClass("dp-month-year-content-with").text("年"));
        $operateLayer.append($dateDiv);
        $operateLayer.append($('<div>').addClass("dp-year-next"));
    }
	/**
	 * 创建日期选择-日期显示界面
	 */
	function buildDateContent($dpDateWrap,cfg){
		var showDate = new Date(cfg.curDate);
		var curYear = showDate.getFullYear();
		var curMonth = showDate.getMonth();
		var curDate = showDate.getDate();
		var maxDate = getMonthMaxDate(cfg);
		
		$dpDateWrap.empty();
		var $dateTable = $("<table>").addClass("ds-date-table");
		$dpDateWrap.append($dateTable);
		var tableHeader = $("<tr>").addClass("ds-date-table-header");
		$dateTable.append(tableHeader);
		$.each(["周日", "周一", "周二", "周三", "周四", "周五", "周六"],function(i, weekStr){
			tableHeader.append($("<th>").addClass("ds-header-cell").text(weekStr));
		});
		
		var tdArr = [];
		var dateLeftPad = new Date(curYear, curMonth, 1).getDay();
		for(var i = dateLeftPad; i > 0; i--){
			var _dateT = new Date(new Date(curYear, curMonth, 1).getTime());
			_dateT.setDate(_dateT.getDate()-i);
			var dateStr = parseInt(_dateT.format("dd"));
			tdArr.push("<td class='ds-date-cell ds-other-month-date'>" + dateStr + "</td>");
		}
		if(curDate > maxDate){
			curDate = maxDate;
		}
		for(var i = 1; i <= maxDate; i++){
			var clazz = "ds-date-cell ds-date-cell-valid";
			if(i == curDate){
				clazz += " ds-date-select";
			}
			tdArr.push("<td class='" + clazz + "'>" + i + "</td>");
		}
		
		var dateRightPad = 6 - new Date(curYear, curMonth, maxDate).getDay();
		for(var i = 1; i <= dateRightPad; i++){
			var _dateT = new Date(new Date(curYear, curMonth, maxDate).getTime());
			_dateT.setDate(_dateT.getDate()+i);
			var dateStr = parseInt(_dateT.format("dd"));
			tdArr.push("<td class='ds-date-cell ds-other-month-date'>" + dateStr + "</td>")
		}
		var maxPad = dateRightPad + (42 - tdArr.length);
		for(var i = dateRightPad + 1; i <= maxPad; i++){
			var _dateT = new Date(new Date(curYear, curMonth, maxDate).getTime());
			_dateT.setDate(_dateT.getDate()+i);
			var dateStr = parseInt(_dateT.format("dd"));
			tdArr.push("<td class='ds-date-cell ds-other-month-date'>" + dateStr + "</td>")
		}
		
		for(var i = 0; i < tdArr.length; i += 7){
			$dateTable.append("<tr>" + tdArr.slice(i, i + 7).join("") + "</tr>");
		}
	}
    /**
     * 创建日期选择-日期显示界面
     */
    function buildDateContentForY($dpDateWrap,cfg){
        var showDate = new Date(cfg.curDate);
        var curYear = showDate.getFullYear();
        var startyear = curYear - 9;
        $dpDateWrap.empty();
        var $dateTable = $("<table>").addClass("dp-date-table");
        $dpDateWrap.append($dateTable);

        var $tr = $("<tr>");
        for(var i = 0; i < 12; i++){
            if(0 == i % 4){
                $tr = $("<tr>");
                $dateTable.append($tr);
            }
            $tr.append($("<td>").css("font-size","14px").addClass("dp-date-cell dp-date-cell-valid").attr("year",startyear).append($("<span>").text(startyear)));
            startyear++;
        }
        $dateTable.find("td[year='"+curYear+"']").addClass("dp-ym-select");
    }
    /**
     * 创建日期选择-日期显示界面
     */
    function buildDateContentForM($dpDateWrap,cfg){
        var showDate = new Date(cfg.curDate);
        var curMonth = showDate.getMonth() + 1;
        $dpDateWrap.empty();
        var $dateTable = $("<table>").addClass("dp-date-table");
        $dpDateWrap.append($dateTable);

        var $tr = $("<tr>");
        $.each([{id : 1, name : "一月"},{id : 2, name : "二月"},{id : 3, name : "三月"},
            {id : 4, name : "四月"},{id : 5, name : "五月"},{id : 6, name : "六月"},
            {id : 7, name : "七月"},{id : 8, name : "八月"},{id : 9, name : "九月"},
            {id : 10, name : "十月"},{id : 11, name : "十一月"},{id : 12, name : "十二月"}],function(i){
            if(0 == i % 4){
                $tr = $("<tr>");
                $dateTable.append($tr);
            }
            $tr.append($("<td>").css("font-size","14px").addClass("dp-date-cell dp-date-cell-valid").attr("month",this.id).append($("<span>").text(this.name)));
        });
        $dateTable.find("td[month='"+curMonth+"']").addClass("dp-ym-select");
    }
	/**
	 * 创建日期选择-小时分钟选择界面
	 */
	function buildHmLayer($dpHmWrap,cfg){
		var showDate = new Date(cfg.curDate);
		var $hourLayerWrap = $("<div>").addClass("ds-hm-select-wrap");
		$dpHmWrap.append($hourLayerWrap);
		var $hourLayer = $("<div>").addClass("ds-hm-select").attr("id","ds-DateHour");
		$hourLayerWrap.append($hourLayer);
		$hourLayerWrap.append("小时");
		var curHour = showDate.format("hh");
		$hourLayer.append($('<div>').addClass("ds-hm-content").text(curHour));
		$hourLayer.append($('<div>').addClass("ds-hm-icon"));
		if(cfg.dateFmt.endsWith("mm")){
			var $minuteLayerWrap = $("<div>").addClass("ds-hm-select-wrap");
			$dpHmWrap.append($minuteLayerWrap);
			var $minuteLayer = $("<div>").addClass("ds-hm-select").attr("id","ds-DateMinute");
			$minuteLayerWrap.append($minuteLayer);
			$minuteLayerWrap.append("分钟");
			var curMinute = showDate.format("mm");
			$minuteLayer.append($('<div>').addClass("ds-hm-content").text(curMinute));
			$minuteLayer.append($('<div>').addClass("ds-hm-icon"));
		}
	}
	
	/**
	 * 绑定日期选择界面上的事件
	 */
	function bindDateEvent($wrap,cfg){
		$wrap.undelegate().delegate(".ds-month-year-content-year","click",function(event){//显示年份选择界面
			event.stopPropagation();
            if(-1 != cfg.dateFmt.indexOf("dd")) {
                if ($(this).hasClass("ds-select")) {
                    $wrap.find(".ds-year-select").hide();
                    $(this).removeClass("ds-select");
                } else {
                    var yearStr = new Date(cfg.curDate).format("yyyy");
                    var $ya = $wrap.find(".ds-year-select .ds-year-area").empty();
                    $.each([0, 5, 1, 6, 2, 7, 3, 8, 4, 9], function (i, m) {
                        $ya.append($('<div>').text(Number(yearStr) + m));
                    });
                    $wrap.find(".ds-year-select").show();
                    $(this).siblings(".ds-month-year-content-month").removeClass("ds-select");
                    $wrap.find(".ds-month-select").hide();
                    $(this).addClass("ds-select");
                }
            }
		}).delegate(".ds-month-year-content-month","click",function(event){//显示月份选择界面
			event.stopPropagation();
			if($(this).hasClass("ds-select")){
				$wrap.find(".ds-month-select").hide();
				$(this).removeClass("ds-select");
			}else{
				$wrap.find(".ds-month-select").show();
				$(this).siblings(".ds-month-year-content-year").removeClass("ds-select");
				$wrap.find(".ds-year-select").hide();
				$(this).addClass("ds-select");
			}
		}).delegate(".ds-year-prev","click",function(event){//上一个年份
			event.stopPropagation();
			var curDate = new Date(cfg.curDate);
			curDate.setFullYear(curDate.getFullYear()-1);
			cfg.curDate = curDate.format(cfg.dateFmt);
			$wrap.find(".ds-month-year-content-year").text(curDate.format("yyyy"));

            $(cfg.appendTo).text(new Date(cfg.curDate).format(cfg.dateFmt));

			buildDateLayer(cfg);
		}).delegate(".ds-year-next","click",function(event){//下一个年份
			event.stopPropagation();
			var curDate = new Date(cfg.curDate);
			curDate.setFullYear(curDate.getFullYear()+1);
            cfg.curDate = curDate.format(cfg.dateFmt);
			$wrap.find(".ds-month-year-content-year").text(curDate.format("yyyy"));

            $(cfg.appendTo).text(new Date(cfg.curDate).format(cfg.dateFmt));

			buildDateLayer(cfg);
		}).delegate(".ds-month-prev","click",function(event){//上一个月份
			event.stopPropagation();
			var curDate = new Date(cfg.curDate);
			curDate.setMonth(curDate.getMonth()-1);
            cfg.curDate = curDate.format(cfg.dateFmt);
			$wrap.find(".ds-month-year-content-month").text(curDate.format("MM"));

            $(cfg.appendTo).text(new Date(cfg.curDate).format(cfg.dateFmt));

			buildDateLayer(cfg);
		}).delegate(".ds-month-next","click",function(event){//下一个月份
			event.stopPropagation();
			var curDate = new Date(cfg.curDate);
			curDate.setMonth(curDate.getMonth()+1);
            cfg.curDate = curDate.format(cfg.dateFmt);
			$wrap.find(".ds-month-year-content-month").text(curDate.format("MM"));

            $(cfg.appendTo).text(new Date(cfg.curDate).format(cfg.dateFmt));

			buildDateLayer(cfg);
		}).delegate(".ds-date-cell-valid","click",function(event){//切换日期
			event.stopPropagation();
			if(!$(this).hasClass("ds-date-select")){
                $wrap.find(".dp-date-table td.dp-date-cell-valid").removeClass("dp-date-select dp-ym-select");
				var curDate = new Date(cfg.curDate);
                if(cfg.dateFmt.endsWith("yyyy")){
                    $(this).addClass("dp-ym-select");
                    curDate.setFullYear($(this).attr("year"));
                }else if(cfg.dateFmt.endsWith("MM")){
                    $(this).addClass("dp-ym-select");
                    curDate.setMonth($(this).attr("month") - 1);
                }else{
                    $(this).addClass("dp-date-select");
                    curDate.setDate($(this).text());
                }
                cfg.curDate = curDate.format(cfg.dateFmt);
				if(-1 == cfg.dateFmt.indexOf("hh")){
					$wrap.find(".date-select-wrap").remove();
				}
                $(cfg.appendTo).text(new Date(cfg.curDate).format(cfg.dateFmt));
			}
		}).delegate("#ds-DateHour","click",function(event){//选择小时
			event.stopPropagation();
			$(this).css("background-color","rgba(51,54,67,0.9)");
			$(this).find(".ds-hm-icon").css({
				"top" : "3px",
				"border-top" : "5px solid transparent",
				"border-bottom" : "5px solid #c1c2ca"
			});
			buildHourOptions($wrap,$(this).parents(".ds-hm-select-wrap"),cfg);
		}).delegate("#ds-DateMinute","click",function(event){//选择分钟
			event.stopPropagation();
			$(this).css("background-color","rgba(51,54,67,0.9)");
			$(this).find(".ds-hm-icon").css({
				"top" : "3px",
				"border-top" : "5px solid transparent",
				"border-bottom" : "5px solid #c1c2ca"
			});
			buildMinuteOptions($wrap,$(this).parents(".ds-hm-select-wrap"),cfg);
		}).delegate(".ds-year-area>div","click",function(event){//选择年份
			event.stopPropagation();
			var showDate = new Date(cfg.curDate);
			showDate.setFullYear(parseInt($(this).text(), 10));
            cfg.curDate = showDate.format(cfg.dateFmt);
			$wrap.find(".ds-year-select").hide();

            $(cfg.appendTo).text(new Date(cfg.curDate).format(cfg.dateFmt));

			buildDateLayer(cfg);
		}).delegate(".ds-year-area-controlleft","click",function(event){//向左切换年份
			event.stopPropagation();
			var yearStr = $wrap.find(".ds-year-select .ds-year-area>div:eq(0)").text();
			var year = parseInt(yearStr, 10) - 10;
			var $ya = $wrap.find(".ds-year-select .ds-year-area").empty();
			$.each([0,5,1,6,2,7,3,8,4,9],function(i,m){
				$ya.append($('<div>').text(year+m));
			});
		}).delegate(".ds-year-area-controlright","click",function(event){//向右切换年份
			event.stopPropagation();
			var yearStr = $wrap.find(".ds-year-select .ds-year-area>div:eq(0)").text();
			var year = parseInt(yearStr, 10) + 10;
			var $ya = $wrap.find(".ds-year-select .ds-year-area").empty();
			$.each([0,5,1,6,2,7,3,8,4,9],function(i,m){
				$ya.append($('<div>').text(year+m));
			});
		}).delegate(".ds-month-select>div","click",function(event){//选择月份
			event.stopPropagation();
			var showDate = new Date(cfg.curDate);
			showDate.setMonth(parseInt($(this).text(), 10)-1);
            cfg.curDate = showDate.format(cfg.dateFmt);
			$wrap.find(".ds-month-select").hide();

            $(cfg.appendTo).text(new Date(cfg.curDate).format(cfg.dateFmt));

			buildDateLayer(cfg);
		});
	}
	/**
	 * 小时选择框
	 */
	function buildHourOptions($wrap,$hourLayerWrap,cfg){
		$wrap.find('.ds-hm-options').remove();
		$wrap.find("#ds-DateMinute").removeAttr("style").find(".ds-hm-icon").removeAttr("style");
		var $hourOptions = $('<div>').addClass("ds-hm-options");
		$hourLayerWrap.append($hourOptions);
		var hourData = [];
		for(var i = 0; i < 24; i++){
			var _curDate = new Date(cfg.curDate);
			if(cfg.dateFmt.endsWith("hh")){
                _curDate.setHours(Math.floor(i/cfg.timeInterval)*cfg.timeInterval);
			}else{
                _curDate.setHours(i);
			}
			var hour = parseInt(_curDate.format("hh"));
			if(-1 == $.inArray(hour,hourData)){
				hourData.push(hour);
			}
		}
		hourData.sort(function(a,b){
			return a-b;
		});
		$hourOptions.height(27 + (32 * Math.ceil(hourData.length / 6)));
		$hourOptions.append($("<div>").addClass("ds-hm-option-title").text("小时选择"));
		var showDate = new Date(cfg.curDate);
		var curHour = showDate.format("hh");
		$.each(hourData,function(i,hour){
			hour = prefixInteger(hour);
			var $hourOption =$("<div>").addClass("ds-hm-option").text(hour);
			if(hour == curHour){
				$hourOption = $("<div>").addClass("ds-hm-option ds-hm-option-selected").text(hour);
			}
			$hourOptions.append($hourOption);
		});
		$hourOptions.find(".ds-hm-option").unbind().bind("click", function(event){
            event.stopPropagation();
			if(!$(this).hasClass("ds-hm-option-selected")){
				$(this).addClass("ds-hm-option-selected").siblings(".ds-hm-option").removeClass("ds-hm-option-selected");
				showDate.setHours(parseInt($(this).text(), 10));
				cfg.curDate = showDate.format("yyyy-MM-dd hh:mm");
				var $parent = $(this).parent().hide().parent();
                $parent.find(".ds-hm-select").removeAttr("style");
                $parent.find(".ds-hm-icon").removeAttr("style");
                $parent.find(".ds-hm-content").text($(this).text());

                $(cfg.appendTo).text(new Date(cfg.curDate).format(cfg.dateFmt));
			}
		});
		$hourOptions.show();
	}
	/**
	 * 分钟选择框
	 */
	function buildMinuteOptions($wrap,$minuteLayerWrap,cfg){
		$wrap.find('.ds-hm-options').remove();
		$wrap.find("#ds-DateHour").removeAttr("style").find(".ds-hm-icon").removeAttr("style");
		var $minuteOptions = $('<div>').addClass("ds-hm-options");
		$minuteLayerWrap.append($minuteOptions);
		var minuteData = [];
		for(var i = 0; i < 60; i++){
			var _curDate = new Date(cfg.curDate);
			_curDate.setMinutes(Math.floor(i/cfg.timeInterval)*cfg.timeInterval);
			var min = parseInt(_curDate.format("mm"));
			if(-1 == $.inArray(min,minuteData)){
				minuteData.push(min);
			}
		}
		minuteData.sort(function(a,b){
			return a-b;
		});
		$minuteOptions.height(27 + (32 * Math.ceil(minuteData.length / 6)));
		$minuteOptions.append($("<div>").addClass("ds-hm-option-title").text("分钟选择"));
		var showDate = new Date(cfg.curDate);
		var curMin = new Date(cfg.curDate).format("mm");
		$(minuteData).each(function(i, minute){
			minute = prefixInteger(minute);
			var $minuteOption = $("<div>").addClass("ds-hm-option").text(minute);
			if(minute == curMin){
				$minuteOption = $("<div>").addClass("ds-hm-option ds-hm-option-selected").text(minute);
			}
			$minuteOptions.append($minuteOption);
		});
		$minuteOptions.find(".ds-hm-option").unbind().bind("click", function(event){
            event.stopPropagation();
			if(!$(this).hasClass("ds-hm-option-selected")){
				$(this).addClass("ds-hm-option-selected").siblings(".ds-hm-option").removeClass("ds-hm-option-selected");
				showDate.setMinutes(parseInt($(this).text(), 10));
				cfg.curDate = showDate.format("yyyy-MM-dd hh:mm");
                var $parent = $(this).parent().hide().parent();
                $parent.find(".ds-hm-select").removeAttr("style");
                $parent.find(".ds-hm-icon").removeAttr("style");
                $parent.find(".ds-hm-content").text($(this).text());

                $(cfg.appendTo).text(new Date(cfg.curDate).format(cfg.dateFmt));
			}
		});
		$minuteOptions.show();
	}
	/**
	 * 自动补0
	 * @param num 需要前面补0的数值
	 * @param n 需要的长度
	 */
	function prefixInteger(num,n){
		if(!n){
			n = 2;
		}
		return (Array(n).join(0)+num).slice(-n);
	}
	/**
	 * 获取月份最大日期
	 */
	function getMonthMaxDate(cfg){
		return dateUtil.getMaxDateForMonth(new Date(cfg.curDate));
	}
	var CFDateselect = function(settings){
		var options = {
            	appendTo: '',//控件容器
				dateFmt : 'yyyy-MM-dd hh:mm',//日期格式
            	isRight : false,//是否与控件容器右对齐
				timeInterval : 5,//时间间隔，默认5分钟
            	curDate: null//控件上的时间
		};
		buildDateLayer($.extend({}, options, settings));
    }
	
	CFDateselect.prototype = {
		remove : function(){
            $(".date-select-wrap").remove();
		}
	};
	
	CafeJS.Dateselect = function(settings){
		var drop =new CFDateselect(settings);
		return drop;
	}
});